set(MANIFEST "${CMAKE_CURRENT_BINARY_DIR}/install_manifest.txt")

if(NOT EXISTS ${MANIFEST})
  message(FATAL_ERROR "Cannot find install manifest: '${MANIFEST}'")
endif()

file(STRINGS ${MANIFEST} files)
foreach(file ${files})
  if(IS_SYMLINK ${file} OR EXISTS ${file})
    message(STATUS "Removing file: '${file}'.")
    exec_program(${CMAKE_COMMAND} ARGS "-E remove ${file}" OUTPUT_VARIABLE stdout RETURN_VALUE result)
    if(NOT "${result}" STREQUAL 0)
      message(FATAL_ERROR "Failed to remove file: '${file}'.")
    endif()
  else()
    message(STATUS "File '${file}' does not exist.")
  endif()
endforeach()

# We will not traverse back and delete "arbitrary" folders.
# An exception are directories which are rtags specific directories like,
# "rtags" under "INSTALL_PREFIX/usr/emacs/site-lisp/".
set(directories "@CMAKE_INSTALL_PREFIX@/share/emacs/site-lisp/rtags")
foreach(dir ${directories})
  if(IS_DIRECTORY ${dir} AND EXISTS ${dir})
    file(GLOB files "${dir}/*")
    if(NOT files)
      message(STATUS "Removing directory: '${dir}'.")
      exec_program(${CMAKE_COMMAND} ARGS "-E remove_directory ${dir}" OUTPUT_VARIABLE stdout RETURN_VALUE result)
      if(NOT "${result}" STREQUAL 0)
	message(FATAL_ERROR "Failed to remove directory: '${dir}'.")
      endif()
    else()
      message(STATUS "Directory '${dir}' not empty.")
    endif()
  else()
    message(STATUS "Directory '${dir}' does not exist.")
  endif()
endforeach()
